package com.factory.iamp.controller;

import com.alibaba.fastjson.JSONObject;
import com.factory.iamp.pojo.User;
import com.factory.iamp.pojo.UserLogin;
import com.factory.iamp.pojo.UserRegister;
import com.factory.iamp.service.GroupService;
import com.factory.iamp.service.RoleService;
import com.factory.iamp.service.TableService;
import com.factory.iamp.service.UserService;
import com.factory.iamp.utils.exception.APIException;
import com.factory.iamp.utils.helper.PageHelper;
import com.factory.iamp.utils.helper.ParamsHelper;
import com.factory.iamp.utils.helper.ResponseCode;
import com.factory.iamp.utils.token.LoginToken;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {
    @Resource
    private UserService userService;

    @Resource
    private RoleService roleService;

    @Resource
    private GroupService groupService;

    @Resource
    private TableService tableService;

    @GetMapping("/overview")
    @LoginToken
    public JSONObject getUserOverview(
            @RequestParam(value = "range", defaultValue = "7") int range,
            @RequestParam(value = "line", defaultValue = "-1") int line,
            @RequestAttribute("iampUser") User user
    ) {
        if(range <= 0) throw new APIException(ResponseCode.VALIDATE_FAILED, "非法时间段");
        if(line == -1) line = user.getLine();
        JSONObject line_result = new JSONObject();
        line_result.put("ToDOOrderNums", userService.ToDoOrderNumsLine(user.getUid(), line));
        line_result.put("MyCreateOrderNums", userService.CreateOrderNumsLine(user.getUid(), line));
        line_result.put("MyRelateOrderNums", userService.RelateOrderNumsLine(user.getUid(), line));
        line_result.put("AllUserNums", userService.CountLine(line));
        line_result.put("AllOrderNums", tableService.Count(line));
        line_result.put("AllToDoOrderNums", tableService.PublishCount(line));
        JSONObject line_SevenDay = tableService.makeSevenDayDataLine(range, line);
        line_result.put("SevenDaySub", line_SevenDay.get("SevenDaySub"));
        line_result.put("SevenDayFault", line_SevenDay.get("SevenDayFault"));
        line_result.put("SevenDayFaultClass", line_SevenDay.get("SevenDayFaultClass"));

        JSONObject result = new JSONObject();
        result.put("ToDOOrderNums", userService.ToDoOrderNums(user.getUid()));
        result.put("MyCreateOrderNums", userService.CreateOrderNums(user.getUid()));
        result.put("MyRelateOrderNums", userService.RelateOrderNums(user.getUid()));
        result.put("AllUserNums", userService.Count());
        result.put("AllOrderNums", tableService.Count(user.getLine()));
        result.put("AllToDoOrderNums", tableService.PublishCount(user.getLine()));
        JSONObject SevenDay = tableService.makeSevenDayData(range);
        result.put("SevenDaySub", SevenDay.get("SevenDaySub"));
        result.put("SevenDayFault", SevenDay.get("SevenDayFault"));
        result.put("SevenDayFaultClass", SevenDay.get("SevenDayFaultClass"));
        result.put("LineData", line_result);
        return result;
    }

    @GetMapping("/info")
    @LoginToken
    public JSONObject getUserInfo(@RequestAttribute("iampUser") User user) {
        JSONObject result = new JSONObject();
        result.put("uid", user.getUid());
        result.put("name", user.getRealname());
        result.put("token", user.makeToken());
        result.put("sign_img", user.getSign_img());
        result.put("role", roleService.findById(user.getRole()));
        result.put("group", groupService.findByUid(user.getUid()));
        result.put("avatar", user.getAvatar());
        result.put("lid", user.getLine());
        return result;
    }

    @GetMapping("/list/{limit}/{page}")
    @LoginToken
    public PageHelper getAllUser(
            @PathVariable("limit") int limit,
            @PathVariable("page") int page,
            @RequestParam(value = "name", defaultValue = "") String name,
            @RequestParam(value = "role", required = false) String role
    ) {
        ParamsHelper paramsHelper = new ParamsHelper(name, role);
        String QueryStr = paramsHelper.makeQueryString();
        PageHelper result = new PageHelper(userService.QueryCount(QueryStr), page, limit);
        result.setData(userService.QueryListPaged(result, QueryStr));
        return result;
    }

    @GetMapping("/find/{limit}/{page}")
    @LoginToken
    public PageHelper findUser(
            @PathVariable("limit") int limit,
            @PathVariable("page") int page,
            @RequestParam("name") String name
    ) {
        name = "%" + name + "%";
        PageHelper result = new PageHelper(userService.findCount(name), page, limit);
        result.setData(userService.findListPaged(result, name));
        return result;
    }

    @GetMapping("/state")
    @LoginToken
    public String checkState() {
        return "正常";
    }

    @PostMapping("/avatar")
    @LoginToken
    public String uploadAvatar(
            @RequestParam("file") MultipartFile file,
            @RequestAttribute("iampUser") User user
    ) throws Throwable {
        return userService.uploadAvatar(user.getUid(), file);
    }

    @PostMapping("/sign")
    @LoginToken
    public String uploadSignImg(
            @RequestParam("file") MultipartFile file,
            @RequestAttribute("iampUser") User user
    ) throws Throwable {
        return userService.uploadSignImg(user.getUid(), file);
    }

    @PostMapping("/login")
    public String Login(@RequestBody @Valid UserLogin user) {
        return userService.Login(user);
    }

    @PostMapping("/register")
    @LoginToken(checkPrivate = true)
    public String Register(@RequestBody @Valid UserRegister user) {
        return userService.Register(user);
    }

    @PostMapping("/logout")
    @LoginToken
    public void Logout(@RequestAttribute("iampUser") User user) {
        userService.Logout(user);
    }

    @PostMapping("/reset")
    @LoginToken(checkPrivate = true)
    public void resetPassword(@RequestBody @Valid User user) {
        userService.resetPassword(user);
    }

    @PostMapping("/passwd")
    @LoginToken
    public void changePassword(
            @RequestAttribute("iampUser") User user,
            @RequestParam("password") String newPassword
    ) {
        userService.changePassword(user, newPassword);
    }

    @DeleteMapping("/delete/{uid}")
    @LoginToken(checkPrivate = true)
    public void deleteUser(@PathVariable("uid") String uid) {
        userService.deleteUser(uid);
    }
}
